package com.hu.job;

import com.hu.dao.UserDao;
import com.hu.pojo.entity.User;
import com.hu.service.UserService;
import com.hu.utils.BloomFilterUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

import static com.hu.constant.UserConstant.FALSE_PROBABILITY;
import static com.hu.constant.UserConstant.USER_DISTINCT_NAME;

/**
 * 重新构建布隆过滤器
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class BloomJob {

    private final UserDao userDao;
    private final BloomFilterUtil bloomFilterUtil;
    private final RedissonClient redissonClient;

    /**
     * 每天
     */
    @Scheduled(cron = "0 0 1 ? * ? ")
    public void run() {
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(USER_DISTINCT_NAME);
        bloomFilter.delete();
        List<User> userList = userDao.list();
        if (CollectionUtils.isEmpty(userList)){
            return;
        }
        bloomFilterUtil.create(USER_DISTINCT_NAME,userList.size(),FALSE_PROBABILITY);
        for (User user : userList) {
            bloomFilter.add(user.getUserName());
        }
    }
}